package com.pi.http.base.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.pi.http.base.model.ParameterRequestWrapper;

/**
 * @author chenmfa
 * @description 判断请求中是否有公共参数, 并对此进行判断, 统一放到{@link #WebMvcConfiguration里面去了}
 */
//@WebFilter(filterName="commParamFilter", urlPatterns="/*")
public class CommParamFilter implements Filter {
  public static final String PARTNER_CODE = "partnerCode";
  public static final String SOURCE_ID = "sourceId";

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    System.out.println(this.getClass() + "init success");
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
          throws IOException, ServletException {
    ParameterRequestWrapper wrapperRequest =
            new ParameterRequestWrapper((HttpServletRequest) request, true, true);
    filterRequestParam(wrapperRequest);
    try {
      chain.doFilter(wrapperRequest, response);
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }

  }

  @Override
  public void destroy() {

  }

  private void filterRequestParam(ParameterRequestWrapper wrapperRequest) {
    Map<String, String[]> parameterMap = wrapperRequest.getParameterMap();
    if (null == parameterMap || parameterMap.size() == 0)
      return;
    //如果是首次创建应用的情况，老的项目默认sourceId和partnerCode相等
    if (!parameterMap.containsKey(SOURCE_ID) && parameterMap.containsKey(PARTNER_CODE)) {
      parameterMap.put(SOURCE_ID, parameterMap.get(PARTNER_CODE));
    }
  }
}
